import { initGlobalState } from 'qiankun'
// import router from '@/router/index.js';
import router from '@/router'
import tab from '@/plugins/tab'
import {
  reactive
} from 'vue'
import pinia from '@/store/index';
import useAppStore from "@/store/modules/app";
import useTagsViewStore from '@/store/modules/tagsView'
const viewStore = useTagsViewStore(pinia)
export const setLoading = (loadingState) => {
  useAppStore(pinia).qiankunLoading = loadingState;
};

import useUserStore from '@/store/modules/user'
import useMatomo from '@/plugins/matomo.ts'
const userData = useUserStore()
const matomos = useMatomo()

// 定义全局下发的数据
let initialState = reactive({
  changeMicoTabsPath: {}, // 微应用tab数据
})

// 初始化全局下发的数据
const actions = initGlobalState(initialState)

actions.onGlobalStateChange((state, prev) => {
  // state: 变更后的状态; prev 变更前的状态
  console.log("state")
  console.log(state)

  for (const key in state) {
    switch (key) {
      // 监听微应用tab切换
      case 'changeMicoTabsPath': {
        let newPathObj = state['changeMicoTabsPath']
        if (newPathObj.type === 'changeLoading') {  // 加载动画
          setLoading(newPathObj.loading)
          initialState['changeMicoTabsPath'] = {};
        } else if (newPathObj.type === 'push') {  // 页面跳转
          router.push({
            ...newPathObj
          })
        }
        else if (newPathObj.type === 'closeTab') {  // 仅关闭当前页面
          const view = viewStore.activeTab
          tab.closePage(view)
        }else if (newPathObj.type === 'closeActiveTab') {  // 关闭当前页面
          const view = viewStore.activeTab
          tab.closePage(view).then(({ visitedViews }) => {
            if (isActive(view)) {
              toLastView(visitedViews, view)
            }
          })
        } else if (newPathObj.type === 'closeOtherTab') { // 关闭其他的的tab
          //待优化
          const view = viewStore.visitedViews.find(v=>v.path == newPathObj.viewPath)
          let fromView = viewStore.visitedViews.find(v=>v.path == newPathObj.backPath) || {}
          viewStore.addFromView(fromView)
          tab.closePage(view).then(({ visitedViews }) => {
            if (isActive(view)) {
              toLastView(visitedViews, view)
            }
          })
        } else if(newPathObj.type === 'closeTabByPath'){    //关闭指定的tab
          const view = viewStore.visitedViews.find(v=>v.path == newPathObj.viewPath)
          if(!view) return
          tab.closePage(view).then(({ visitedViews }) => {
            if (isActive(view)) {
              toLastView(visitedViews, view)
            }
          })
        }
        break;
      }
      default:
        initialState[key] = state[key]
        break;
    }
  }
});

// 定义一个获取state的方法下发到子应用
actions.getGlobalState = async function (key) {
  switch (key) {
    default:
      return key ? initialState[key] : initialState
  }
}

// 定义一个 matomo 
actions.handleMatomo = async function (handleDom) {
  if(!handleDom.event) return
  // 当前操作页名称
  let pageTitle = document.getElementsByClassName('matomo-page-title router-link-active router-link-exact-active active tags-view-item')?.[0]?.innerText || '暂无'
  matomos.setUserId(`${userData.name}(${userData.user_id})`)
  matomos.trackPageView(pageTitle)
  matomos.trackEvent('点击操作',handleDom.event, '-')
}
function toLastView(visitedViews, view) {
  const latestView = (viewStore.fromView.fullPath ? viewStore.fromView : null)  || visitedViews.slice(-1)[0]
  if (latestView) {
    router.push(latestView.fullPath)
  } else {
    if (view.name === 'Index') {
      router.replace({ path: '/redirect' + view.fullPath })
    } else {
      router.push('/index')
    }
  }
}
function isActive(r) {
  const { path } = router.currentRoute.value;

  return r.path === path
}


export default actions
